package com.hthy.futures.ui.fragment;

import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;

import com.bigkoo.pickerview.TimePickerView;
import com.hthy.futures.R;
import com.hthy.futures.adapter.BillSearchAdapter;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.base.BaseFragment;
import com.hthy.futures.bean.BillSearchBean;
import com.hthy.futures.bean.Goods;
import com.hthy.futures.utils.DataUtils;
import com.hthy.futures.utils.ErrorUtils;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.StringUtils;
import com.hthy.futures.view.EmptyLayout;
import com.vilyever.socketclient.SocketClient;

import net.hthy.bean.Trade;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.Bind;

/**
 * 单据查询
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/6
 */

public class BillSearchFragment extends BaseFragment {
    @Bind(R.id.listView)
    ListView mListView;
    @Bind(R.id.rg)
    RadioGroup mGroup;
    @Bind(R.id.bt_from)
    Button btFrom;
    @Bind(R.id.bt_to)
    Button btTo;

    @Bind(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @Bind(R.id.ll_search_condition)
    LinearLayout mSearchConditionView;

    private BillSearchAdapter mAdapter;

    List<BillSearchBean> myTodayBillsearch = new ArrayList<>();


    private String mFromTime;  // 起止时间
    private String mEndTime;  // 结束时间
    private boolean isFromToday;
    private boolean isFromMonth;
    private boolean isFromThreeMonth;
    private boolean isFromCustomize;
    private boolean isFromBillSeach;
    private List<Goods> mGoodList = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.frag_bill_search;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mAdapter = new BillSearchAdapter(getActivity(), R.layout.adapter_seach_bill);
        mListView.setAdapter(mAdapter);

        // 应该第一步获取商品的信息
        // 获取商品种类
        socketClient.sendData(ST_TradeApi.searchGoods("2015"));
        isFromBillSeach = true;


        mSearchConditionView.setVisibility(View.GONE);

        mGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.bt_day:           // 单日
                        // getTimeDaty(DataUtils.getTimesmorning(), DataUtils.getTimesnight());
                        getToday();
                      /*  DataUtils.getTimesmorning();
                        DataUtils.getTimesnight();*/

                        mSearchConditionView.setVisibility(View.GONE);
                        break;
                    case R.id.bt_month:  // 本月
                        getTimeDaty(DataUtils.getTimesMonthmorning(), DataUtils.getTimesMonthnight());

                        /*DataUtils.getTimesMonthmorning();
                        DataUtils.getTimesMonthnight();*/
                        isFromMonth = true;
                        mSearchConditionView.setVisibility(View.GONE);
                        break;
                    case R.id.bt_three_month:  // 近三月
                        getTimeDaty(DataUtils.getThreeTime(), DataUtils.getToday());
                        // DataUtils.getThreeTime();
                        isFromThreeMonth = true;
                        mSearchConditionView.setVisibility(View.GONE);
                        break;
                    case R.id.bt_custom_month:
                        isFromCustomize = true;
                        mSearchConditionView.setVisibility(View.VISIBLE);
                        if (mAdapter.getDatas().size() > 0) {
                            mAdapter.clear();
                        }
                        mAdapter.notifyDataSetChanged();

                        // 如果有之前的值的话，直接查询
                        if (!StringUtils.isEmpty(mFromTime) && !StringUtils.isEmpty(mEndTime)) {
                            if (compareTime()) return;
                            getTimeDaty(mFromTime, mEndTime);
                        }
                        break;
                }
            }
        });

        // 起止时间
        btFrom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调


                        mFromTime = getTime(date);
                        // 如果结束时间有的话也得做比较
                        if (!StringUtils.isEmpty(mEndTime)) {
                            if (compareTime()) return;
                        }
                        btFrom.setText(mFromTime);
                        if (!StringUtils.isEmpty(mEndTime)) {
                            getTimeDaty(mFromTime, mEndTime);
                        }

                    }
                }).setType(TimePickerView.Type.YEAR_MONTH_DAY).build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        // 结束时间
        btTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        if (mFromTime == null) {
                            showToast(R.string.choose_from_time);
                            return;
                        }
                        // 2017-03-31
                        mEndTime = getTime(date);
                        if (compareTime()) return;
                        // 当选择结束的时候，和起止时间做判断，如果大于则正常，去请求接口
                        btTo.setText(mEndTime);
                        getTimeDaty(mFromTime, mEndTime);
                    }
                }).setType(TimePickerView.Type.YEAR_MONTH_DAY).build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });


    }

    /**
     * 比较时间的合理性
     *
     * @return
     */
    private boolean compareTime() {
        int i = DataUtils.compare_date(mFromTime, mEndTime);
        if (i == 0) {
            showToast(R.string.time_tip1);
            return true;
        } else if (i == 1) {
            showToast(R.string.time_tip2);
            return true;
        }
        return false;
    }


    /**
     * 查询单天的
     */
    private void getToday() {
        // 2005  是查单天的
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        socketClient.sendData(ST_TradeApi.searchGoods("2005"));
        isFromToday = true;
    }

    /**
     * 查询历史的
     *
     * @param timesmorning
     * @param timesnight
     */
    private void getTimeDaty(String timesmorning, String timesnight) {
        // 2005  是查单天的
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        socketClient.sendData(ST_TradeApi.seachHistoryData("2013", timesmorning, timesnight));
    }

    @Override
    protected void onResponse(SocketClient client, String responMes, byte[] subBytes) {
        super.onResponse(client, responMes, subBytes);
        LogUtils.e("BillSearchFragment", responMes);
        //从查询交易商品获取
        if (isFromBillSeach && responMes.indexOf("2016") != -1) {
            try {
                Trade.QueryProductsResponseMsg queryProductsResponseMsg = Trade.QueryProductsResponseMsg.parseFrom(subBytes);
                List<Trade.UserProductsInfo> userProductsInfoList = queryProductsResponseMsg.getUserProductsInfoList();
                for (Trade.UserProductsInfo productsInfo : userProductsInfoList) {
                    Goods goods = new Goods();
                    goods.setSs_product_code(productsInfo.getSsProductCode());
                    goods.setSs_product_name(productsInfo.getSsProductName());
                    goods.setUi_buy_pips(productsInfo.getUiBuyPips() + "");
                    goods.setUi_sell_pips(productsInfo.getUiSellPips() + "");
                    goods.setUi_sl_pips(productsInfo.getUiSlPips() + "");
                    goods.setUi_tp_pips(productsInfo.getUiTpPips() + "");
                    goods.setDb_contract_size(productsInfo.getDbContractSize() + "");
                    goods.setDb_origin_margin(productsInfo.getDbOriginMargin() + "");
                    goods.setUi_margin_type(productsInfo.getUiMarginType() + "");
                    mGoodList.add(goods);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            isFromBillSeach = false;
            getToday();
            isFromToday = true;
        } else if (isFromToday && responMes.indexOf("2006") != -1) {
            searchHistoryData(subBytes, 0);
            isFromToday = false;
        } else {
            searchHistoryData(subBytes, 1);
        }
    }

    /**
     * 处理历史数据   0代表的是求单日的数据，需要筛选的
     */
    private void searchHistoryData(byte[] subBytes, int flag) {
        try {
            Trade.QueryOrderResponseMsg queryOrderResponseMsg = Trade.QueryOrderResponseMsg.parseFrom(subBytes);
            int iErrorCode = queryOrderResponseMsg.getResponseMsg().getIErrorCode();
            if (0 == iErrorCode) {   // 0说明是正确返回的
                List<Trade.UserOrderDetail> orderDetailList = queryOrderResponseMsg.getOrderDetailList();
                if (orderDetailList != null && orderDetailList.size() > 0) {
                    mEmptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    List<BillSearchBean> datas = new ArrayList<>();
                    for (Trade.UserOrderDetail userOrderDetail : orderDetailList) {
                        BillSearchBean billSearchBean = new BillSearchBean();
                        billSearchBean.setDbExecuteSize(userOrderDetail.getDbExecuteSize()+"");
                        billSearchBean.setDbOrderSize(userOrderDetail.getDbOrderSize()+"");
                        billSearchBean.setOrderStatusValue(userOrderDetail.getOrderStatusValue()+"");
                        billSearchBean.setOrderDirectionValue(userOrderDetail.getOrderDirectionValue()+"");
                        billSearchBean.setSsProductCode(userOrderDetail.getSsProductCode() + "");
                        billSearchBean.setSsExecuteTime(userOrderDetail.getSsExecuteTime());
                        billSearchBean.setDbTpPrice(userOrderDetail.getDbTpPrice()+"");
                        billSearchBean.setDbSlPrice(userOrderDetail.getDbSlPrice()+"");
                        billSearchBean.setLimitOrderTypeValue(userOrderDetail.getLimitOrderTypeValue()+"");
                        billSearchBean.setDbHoldPrice(userOrderDetail.getDbHoldPrice()+"");
                        billSearchBean.setExecuteTime(userOrderDetail.getSsExecuteTime());
                        billSearchBean.setDbCloseOrderSize(userOrderDetail.getDbCloseOrderSize()+"");
                        billSearchBean.setDbClosePrice(userOrderDetail.getDbClosePrice()+"");
                        billSearchBean.setSsCloseTime(userOrderDetail.getSsCloseTime());
                        billSearchBean.setUiOrderCloseStatus(userOrderDetail.getUiOrderCloseStatus() == 49 ? "1" : "2");
                        billSearchBean.setUiOrderUid(userOrderDetail.getUiOrderUid()+"");
                        billSearchBean.setDbOpenClosePl(userOrderDetail.getDbOpenClosePl()+"");
                        billSearchBean.setDbTotalSwap(userOrderDetail.getDbTotalSwap()+"");
                        billSearchBean.setDbOrderPrice(userOrderDetail.getDbOrderPrice()+"");
                        datas.add(billSearchBean);
                    }

                    myTodayBillsearch.clear();
                    if (mAdapter.getDatas().size() > 0) {
                        mAdapter.clear();
                    }
                    if (flag == 0) {
                        for (BillSearchBean billSearchBean : datas) {
                            if (billSearchBean.getOrderStatusValue().equals("2") && billSearchBean.getUiOrderCloseStatus().equals("2")) {
                                myTodayBillsearch.add(billSearchBean);
                            }
                        }
                    } else {
                        myTodayBillsearch = datas;
                    }

                    // 把商品屬性賦值給orderticket

                    List<BillSearchBean> myTodayBillsearchTmp = new ArrayList<>();
                    for (BillSearchBean billSearchBean : myTodayBillsearch) {
                        for (Goods goods : mGoodList) {
                            if (billSearchBean.getSsProductCode().equals(goods.getSs_product_code())) {
                                // 这个时候赋值操作
                                billSearchBean.buyPriceSpreed = goods.getUi_buy_pips();
                                billSearchBean.sellPriceSpreed = goods.getUi_sell_pips();

                                billSearchBean.order_s_spread = goods.getUi_sl_pips();
                                billSearchBean.order_y_spread = goods.getUi_tp_pips();

                                billSearchBean.contractUnit = goods.getDb_contract_size();  // 合约单位

                                // 为了计算保证金，得从goods里面得到初始保证金以及合约单位
                                billSearchBean.initGuaranteeMoney = goods.getDb_origin_margin(); // 初始保障金
                                billSearchBean.moneyHoldType = goods.getUi_margin_type(); // 保证金类型
                                myTodayBillsearchTmp.add(billSearchBean);
                            }
                        }
                    }

                    if (myTodayBillsearchTmp.size() > 0) {
                        Collections.reverse(myTodayBillsearchTmp);
                    }
                    mAdapter.addItem(myTodayBillsearchTmp);
                } else {
                    mEmptyLayout.setErrorType(EmptyLayout.NODATA);
                    return;
                }

            } else {
                ErrorUtils.sendErrorMes(getActivity(), iErrorCode + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

}
